<template>
  <div>
    <el-upload
      :limit="4"
      :action="actionUrl"
      :file-list="fileList"
      :on-exceed="handExceed"
      :http-request="imgSizeFun"
      :on-remove="handleRemove"
      list-type="picture-card">
      <i class="el-icon-plus"/>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  /* eslint-disable vue/require-prop-types */
  props: ['type', 'editorData'],
  data() {
    return {
      actionUrl: '',
      fileList: []
    }
  },
  beforeMount() {
    if (this.type !== 1) {
      if (this.editorData.img) {
        const splitimg = this.editorData.img.split(',')
        for (const val of splitimg) {
          const obj = {}
          obj.url = val
          this.fileList.push(obj)
        }
      }
    }
  },
  created() {
    this.initUploadFileurl()
  },
  methods: {
    initUploadFileurl() {
      this.actionUrl = process.env.BASE_API + 'file/uploadImageAndCrtThumbImagesRichEdit'
      this.uploadUrl = process.env.BASE_API + 'file/uploadFiles'
    },
    imgSizeFun(condent) {
      // 上传图片前处理函数
      const file = condent.file
      const isJPG =
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/gif'
      const isLt2M = file.size < 1048576
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 jpg、png、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1M!')
        return false
      }
      const fd = new FormData()
      fd.append('images', file)
      fd.append('resPath', this.resPath)
      const loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      axios.post(condent.action, fd).then(res => {
        loading.close()
        if (res.data.code === 1) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          const obj = {}
          obj.url = res.data.data[0].maxImageUrl
          this.fileList.push(obj)
          this.$emit('emitSuccess', this.fileList)
        } else {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        }
      }).catch(res => {
        this.$message({
          type: 'info',
          message: res.message
        })
        loading.close()
      })
    },
    handleRemove(file, fileList) {
      var _this = this
      this.fileList.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.fileList.splice(index, 1)
        }
      })
      this.$emit('emitSuccess', this.fileList)
    },
    handExceed(files, fileList) {
      this.$message({
        message: '最多上传4张图片',
        type: 'warning'
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
